package com.awaken.content.service.impl;

import com.awaken.content.mapper.UserMapper;
import com.awaken.content.mapper.UserSessionMapper;
import com.awaken.content.mapper.VerificationCodeMapper;
import com.awaken.content.models.dto.LoginResultDTO;
import com.awaken.content.models.entity.User;
import com.awaken.content.models.entity.UserSession;
import com.awaken.content.models.entity.VerificationCode;
import com.awaken.content.models.request.LoginRequest;
import com.awaken.content.models.request.RegisterRequest;
import com.awaken.content.models.request.SendVerificationCodeRequest;
import com.awaken.content.service.AuthService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.UUID;

@Service
public class AuthServiceImpl extends ServiceImpl<UserSessionMapper, UserSession> implements AuthService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private VerificationCodeMapper verificationCodeMapper;
    
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    
    @Override
    public LoginResultDTO login(LoginRequest request) {
        LoginResultDTO result = new LoginResultDTO();
        
        // 根据用户名查找用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", request.getUsername());
        User user = userMapper.selectOne(queryWrapper);
        
        if (user == null) {
            result.setSuccess(false);
            result.setMessage("用户名不存在");
            return result;
        }
        
        // 验证密码
        if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
            result.setSuccess(false);
            result.setMessage("密码错误");
            return result;
        }
        
        // 检查用户状态
        if (user.getStatus() != 1) {
            result.setSuccess(false);
            result.setMessage("账户已被禁用");
            return result;
        }
        
        // 生成会话令牌
        String sessionToken = UUID.randomUUID().toString();
        LocalDateTime expireTime = request.getRememberMe() != null && request.getRememberMe() 
            ? LocalDateTime.now().plusDays(30) 
            : LocalDateTime.now().plusHours(24);
        
        // 保存会话
        UserSession session = new UserSession();
        session.setUserId(user.getId());
        session.setSessionToken(sessionToken);
        session.setExpireTime(expireTime);
        session.setCreateTime(LocalDateTime.now());
        save(session);
        
        // 返回登录结果
        result.setSuccess(true);
        result.setUserId(user.getId());
        result.setUsername(user.getUsername());
        result.setEmail(user.getEmail());
        result.setAvatar(user.getAvatar());
        result.setSessionToken(sessionToken);
        result.setExpireTime(expireTime.toEpochSecond(java.time.ZoneOffset.UTC) * 1000);
        result.setMessage("登录成功");
        
        return result;
    }
    
    @Override
    public LoginResultDTO register(RegisterRequest request) {
        LoginResultDTO result = new LoginResultDTO();
        
        // 验证密码确认
        if (!request.getPassword().equals(request.getConfirmPassword())) {
            result.setSuccess(false);
            result.setMessage("两次输入的密码不一致");
            return result;
        }
        
        // 检查用户名是否已存在
        QueryWrapper<User> usernameQuery = new QueryWrapper<>();
        usernameQuery.eq("username", request.getUsername());
        if (userMapper.selectOne(usernameQuery) != null) {
            result.setSuccess(false);
            result.setMessage("用户名已存在");
            return result;
        }
        
        // 检查邮箱是否已存在
        if (request.getEmail() != null) {
            QueryWrapper<User> emailQuery = new QueryWrapper<>();
            emailQuery.eq("email", request.getEmail());
            if (userMapper.selectOne(emailQuery) != null) {
                result.setSuccess(false);
                result.setMessage("邮箱已被注册");
                return result;
            }
        }
        
        // 验证验证码
        if (!verifyCode(request.getEmail(), request.getVerificationCode(), 1)) {
            result.setSuccess(false);
            result.setMessage("验证码错误或已过期");
            return result;
        }
        
        // 创建新用户
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(passwordEncoder.encode(request.getPassword()));
        user.setEmail(request.getEmail());
        user.setPhone(request.getPhone());
        user.setStatus(1);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        
        userMapper.insert(user);
        
        // 自动登录
        LoginRequest loginRequest = new LoginRequest();
        loginRequest.setUsername(request.getUsername());
        loginRequest.setPassword(request.getPassword());
        loginRequest.setRememberMe(false);
        
        return login(loginRequest);
    }
    
    @Override
    public void logout(String sessionToken) {
        QueryWrapper<UserSession> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("session_token", sessionToken);
        remove(queryWrapper);
    }
    
    @Override
    public Boolean sendVerificationCode(SendVerificationCodeRequest request) {
        // 检查是否在5分钟内已发送过验证码
        QueryWrapper<VerificationCode> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", request.getEmail())
                .eq("type", request.getType())
                .eq("used", 0)
                .gt("expire_time", LocalDateTime.now())
                .orderByDesc("create_time")
                .last("LIMIT 1");
        
        VerificationCode existingCode = verificationCodeMapper.selectOne(queryWrapper);
        if (existingCode != null) {
            LocalDateTime fiveMinutesAgo = LocalDateTime.now().minusMinutes(5);
            if (existingCode.getCreateTime().isAfter(fiveMinutesAgo)) {
                return false; // 5分钟内已发送过验证码
            }
        }
        
        // 生成验证码
        String code = String.format("%06d", (int) (Math.random() * 1000000));
        
        // 保存验证码
        VerificationCode verificationCode = new VerificationCode();
        verificationCode.setEmail(request.getEmail());
        verificationCode.setCode(code);
        verificationCode.setType(request.getType());
        verificationCode.setExpireTime(LocalDateTime.now().plusMinutes(10));
        verificationCode.setUsed(0);
        verificationCode.setCreateTime(LocalDateTime.now());
        
        verificationCodeMapper.insert(verificationCode);
        
        // TODO: 这里应该发送邮件，暂时返回true
        System.out.println("验证码: " + code);
        
        return true;
    }
    
    @Override
    public Boolean verifyCode(String email, String code, Integer type) {
        QueryWrapper<VerificationCode> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email)
                .eq("code", code)
                .eq("type", type)
                .eq("used", 0)
                .gt("expire_time", LocalDateTime.now())
                .orderByDesc("create_time")
                .last("LIMIT 1");
        
        VerificationCode verificationCode = verificationCodeMapper.selectOne(queryWrapper);
        if (verificationCode == null) {
            return false;
        }
        
        // 标记验证码为已使用
        verificationCode.setUsed(1);
        verificationCodeMapper.updateById(verificationCode);
        
        return true;
    }
    
    @Override
    public LoginResultDTO validateSession(String sessionToken) {
        LoginResultDTO result = new LoginResultDTO();
        
        QueryWrapper<UserSession> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("session_token", sessionToken)
                .gt("expire_time", LocalDateTime.now());
        
        UserSession session = getOne(queryWrapper);
        if (session == null) {
            result.setSuccess(false);
            result.setMessage("会话已过期");
            return result;
        }
        
        // 获取用户信息
        User user = userMapper.selectById(session.getUserId());
        if (user == null || user.getStatus() != 1) {
            result.setSuccess(false);
            result.setMessage("用户不存在或已被禁用");
            return result;
        }
        
        result.setSuccess(true);
        result.setUserId(user.getId());
        result.setUsername(user.getUsername());
        result.setEmail(user.getEmail());
        result.setAvatar(user.getAvatar());
        result.setSessionToken(sessionToken);
        result.setExpireTime(session.getExpireTime().toEpochSecond(java.time.ZoneOffset.UTC) * 1000);
        result.setMessage("会话有效");
        
        return result;
    }
} 